#!/usr/bin/python
# coding=UTF-8
import tvrage, showdb

from sqlobject import SQLObjectNotFound

def _update_episode(show, season, episode):
	print "update_episode", show.name.encode('UTF-8'), season.number, episode.number
	data = tvrage.read(show = show.name, ep = '%02dx%02d' % (season.number, episode.number))
	title, date = tvrage.get_episode_info(data)
	if not title:
		title = ''
	episode.set(title = title, date = date)

def _fill_season(show, season, number):
	while True:
		data = tvrage.read(show = show.name, ep = '%02dx%02d' % (season.number, number))
		if not data.has_key('Episode Info'):
			break
		title, date = tvrage.get_episode_info(data)
		showdb.Episode(season = season,
			number = number,
			title = title,
			date = date)
		number += 1

def _update_season(show, season, last_date = None):
	print "update_season", show.name.encode('UTF-8'), season.number
	last_episode = None
	for episode in season.episodes:
		if not last_episode or episode.number > last_episode.number:
			last_episode = episode
		if not last_date or not episode.date or episode.date > last_date or episode.title == '':
			_update_episode(show, season, episode)
	_fill_season(show, season, last_episode and last_episode.number + 1 or 1)

def _fill_show(show, number):
	while True:
		data = tvrage.read(show = show.name, ep = '%02dx%02d' % (number, 1))
		if not data.has_key('Episode Info'):
			break
		season = showdb.Season(show = show, number = number)
		_update_season(show, season)
		number += 1

def _update_show(show, last_date = None):
	print "update_show", show.name.encode('UTF-8')
	data = tvrage.read(show = show.name)
	if data.has_key('Status') and data['Status'] == u'Canceled/Ended':
		show.skipUpdate = True
	else:
		show.skipUpdate = False
	last_season = None
	for season in show.seasons:
		if not last_season or season.number > last_season.number:
			last_season = season
	if last_season:
		_update_season(show, last_season, last_date)
	_fill_show(show, last_season and last_season.number + 1 or 1)

def update(last_date = None):
	for show in showdb.Show.select(showdb.Show.q.skipUpdate == False):
		_update_show(show, last_date)

def check_unknown_shows():
	found = []
	for entry in showdb.UnknownShows.select(showdb.UnknownShows.q.checked == False):
		entry.checked = True
		print "check_show", entry.name.encode('UTF-8')
		data = tvrage.read(show = entry.name)
		if data and data.has_key('Show Name'):
			try:
				show = showdb.Show.byName(data['Show Name'])
			except SQLObjectNotFound:
				show = showdb.Show(name = data['Show Name'])
				if data.has_key('Country'):
					show.country = data['Country']
				if data.has_key('Status'):
					show.status = data['Status']
				if data.has_key('Classification'):
					show.classification = data['Classification']
				if data.has_key('Genres'):
					show.genres = data['Genres']
				if data.has_key('Network'):
					show.network = data['Network']
				if data.has_key('Airtime'):
					show.airtime = data['Airtime']
				if data.has_key('Runtime'):
					show.runtime = int(data['Runtime'])
				_update_show(show)
			if show.name != entry.name:
				showdb.ShowAlternateNames(name = entry.name, show = show)
			found.append(entry.id)

	for id in found:
		showdb.UnknownShows.delete(id)

if __name__ == '__main__':
	import datetime

	showdb.init()
	date = datetime.date.today() - datetime.timedelta(days = 7)
	update(date)
	check_unknown_shows()
